<?php # RoomAvailabilitySearch.php
require "star_ratings.class.php";
require "country.class.php";
require "address.class.php";
require "hotels.class.php";
require "customers.class.php";
require "roombookings.class.php";
require "bookings.class.php";
require "rooms.class.php";
require "roomtypes.class.php";

/*
 * Specify the field names that are in the form.
 */
$allowedFields = array(
 			'indate',
			'outdate',
			'bedtype', // options king, queen, or twin
			'smoking', // options yes or no
			'maxprice', // float
			'minprice', // float
			'latitude', // integer
			'longitude', // integer
			'maxdistance', // integer
      'dest'
);

/*
 * Specify the field names that are required...
 */
$requiredFields = array(
			'indate',
			'outdate'
);


$error = false;
$message = array();
foreach($_GET AS $key => $value)
{
	// first make sure this is an allowed field
	if(in_array($key, $allowedFields))
	{
		$$key = $value;
		
		// is this a required field?
		if(in_array($key, $requiredFields) && $value == '')
		{
			$error = true;
			array_push($message, 'The field '.$key.' is required.');
		}
	}
	else
	{
		$error = true;
		array_push($message, 'The field '.$key.' does not exist.');
	}
}

if (!$error) {
	if (isset($_GET['indate'])){
		$searchindate = strtotime($_GET['indate']);
	}
	else {
		$searchindate = '';
	}
	if (isset($_GET['outdate'])){
		$searchoutdate = strtotime($_GET['outdate']);
	}
	else {
		$searchoutdate = '';
  }
  if(isset($_GET['dest'])) {
    $searchdestination = $_GET['dest'];
  }
  else {
    $searchdestination = '';
  }

	if (isset($_GET['bedtype'])){
		$searchbedtype = $_GET['bedtype'];
	}
	else {
		$searchbedtype = '';
	}
	if (isset($_GET['smoking'])){
		$searchsmoking = $_GET['smoking'];
	}
	else {
		$searchsmoking = '';
	}
	if (isset($_GET['maxprice'])){
		$searchmaxprice = $_GET['maxprice'];
	}
	else {
		$searchmaxprice = '';
	}
	if (isset($_GET['minprice'])){
		$searchminprice = $_GET['minprice'];
	}
	else {
		$searchminprice = '';
	}
	if (isset($_GET['latitude'])){
		$searchlatitude = $_GET['latitude'];
	}
	else {
		$searchlatitude = '';
	}
	if (isset($_GET['longitude'])){
		$searchlongitude = $_GET['longitude'];
	}
	else {
		$searchlongitude = '';
	}
	if (isset($_GET['maxdistance'])){
		$searchmaxdistance = $_GET['maxdistance'];
	}
	else {
		$searchmaxdistance = '';
	}
	
	$hotels = Hotels::loadAll();
	$return_arr = array();
	
	$count = count($hotels);
	$total = 0;
	for ($i = 0; $i < $count; $i++) {
		$hotel_array = array();
		
		// set up the room type count array.  keeps track of how many rooms are available for each type in a hotel.
		$availableRoomtypeCount = array();
		$allRoomTypes = Roomtypes::loadAll();
		for ($r = 0; $r < count($allRoomTypes); $r++) {
			$roomTypeId = $allRoomTypes[$r]->getRoomTypeCode();
			$availableRoomtypeCount[$roomTypeId] = 0;
		}
		
		// retrieve the information about the hotel
		$hotel_info_array = array();
		$hotelId = $hotels[$i]->getHotelId();
		$hotelName = $hotels[$i]->getHotelName();
		$hotelURL = $hotels[$i]->getHotelURL();
		$address = $hotels[$i]->getAddress();
		$country = $hotels[$i]->getCountry()->getCountryName();
		$starRating = $hotels[$i]->getStarRatings()->getStarRatingDescription();
		$latitude = $address->getLatitude();
		$longitude = $address->getLongitude();
		$street = $address->getStreet();
		$city = $address->getCity();
		$stateOrProvince = $address->getStateOrProvince();
		$postalCode = $address->getPostalCode();
		
      if($searchdestination != '') {
      $hasCity = -1;
      $hasState = -1;
      $containsCity = stripos($searchdestination, $city);
      $containsState = stripos($searchdestination, $stateOrProvince);
      if($containsCity !== FALSE) {
      $hasCity = 0;
      }
      if($containsState !== FALSE) {
      $hasState = 0;
      }
      if($hasCity == -1 || $hasState == -1) {
      continue;
      }
      }


		// search for hotel based on latitude
		if($searchlatitude != '') {
			if($latitude != $searchlatitude) { // Hotel doesn't match the latitude search criteria.  Continue to next hotel.
				continue;
			}
		}
		
		// search for hotel based on longitude
		if($searchlongitude != '') {
			if($longitude != $searchlongitude) { // Hotel doesn't match the longitude search criteria. Continue to next hotel.
				continue;
			}
		}
		
		// search for hotel based on maxdistance
		if($searchmaxdistance != '') {
			// not sure what to do here right now.
		}
		
		// hotel meets the search criteria, so add it to the array.
		$hotel_info_array['hotelId'] = $hotelId;
		$hotel_info_array['hotelName'] = $hotelName;
		$hotel_info_array['hotelURL'] = $hotelURL;
		$hotel_info_array['starRating'] = $starRating;
		$hotel_info_array['streetAddress'] = $street;
		$hotel_info_array['city'] = $city;
		$hotel_info_array['stateOrProvince'] = $stateOrProvince;
		$hotel_info_array['postalCode'] = $postalCode;
		$hotel_info_array['country'] = $country;
		$hotel_info_array['latitude'] = $latitude;
		$hotel_info_array['longitude'] = $longitude;
		$hotel_array['hotel_info'] = $hotel_info_array;
		
		// retrieve all the rooms for the hotel
		$hotelRooms = $hotels[$i]->getRoomss();
		$totalRooms = count($hotelRooms);
		for ($j = 0; $j < $totalRooms; $j++) {  // loop through all the rooms to find the available room types base upon the search criteria
			
			$roomId = $hotelRooms[$j]->getRoomId();
			$roomType = $hotelRooms[$j]->getRoomtypes();
			$roomTypeCode = $roomType->getRoomTypeCode();
			$roomStandardRate = $roomType->getRoomStandardRate();
			$roomTypeDescription = $roomType->getRoomTypeDescription();
			$roomSmokingYN = $roomType->getSmokingYN();
			
			// search for room types based on smoking
			if($searchsmoking != '') {
				if($roomSmokingYN != $searchsmoking) { // Room doesn't match the smoking search criteria.  Continue to next room.
					continue;
				}
			}
			
			// search for room types based on maxprice
			if($searchmaxprice != '') {
				if($roomStandardRate > $searchmaxprice) { // Room doesn't match the max pricing criteria. Continue to next room.
					continue;
				}
			}
			
			// search for room types based on minprice
			if($searchminprice != '') {
				if($roomStandardRate < $searchminprice) { // Room doesn't match the min pricing criteria. Continue to next room.
					continue;
				}
			}
			
			// search for room types based on bed type
			if($searchbedtype != '') {
				if($searchbedtype == 'king') {
					$containsBedType = stripos($roomTypeCode, 'k');
				}
				else if($searchbedtype == 'queen') {
					$containsBedType = stripos($roomTypeCode, 'q');
				}
				else if($searchbedtype == 'twin') {
					$containsBedType = stripos($roomTypeCode, 't');
				}
				else {
					$containsBedType = -1;
				}
				if($containsBedType !== 0) {
					continue;
				}
			}
			
			// get the room bookings if any
			$roomBookings = $hotelRooms[$j]->getRoombookingss(); // array
			$totalRoomBookings = count($roomBookings);
			if($totalRoomBookings == 0) { // room is available because it has never been booked.
				$availableRoomtypeCount[$roomTypeCode]++;
			}
			else {
				// check to see if the room is available based upon the search criteria for indate and outdate.
				// if the room is available then increment the availableRoomtypeCount.  Keeps track of how many
				// rooms for the specific room type are available for the specified search criteria.
				$isRoomAvailable = false;
				for ($k = 0; $k < count($roomBookings); $k++) {
					$booking = $roomBookings[$k]->getBookings();
					$dateFrom = strtotime($booking->getDateFrom());
					$dateTo = strtotime($booking->getDateTo());
					
					if(($searchindate < $dateFrom && $searchoutdate <= $dateFrom) || ($searchindate >= $dateTo && $searchoutdate > $dateTo)) {
						$isRoomAvailable = true;
					}
					else {
						$isRoomAvailable = false;
					}
				}
				if($isRoomAvailable == true) {
					$availableRoomtypeCount[$roomTypeCode]++;
				}
			}
		}
		$roomtypeInfo_array = array();
		$roomtypes_array = array();
		// find all the room types that have a count > 0 and add them to the room type array.
		for ($r = 0; $r < count($allRoomTypes); $r++) {
			$roomTypeId = $allRoomTypes[$r]->getRoomTypeCode();
			$standardRate = $allRoomTypes[$r]->getRoomStandardRate();
			$description = $allRoomTypes[$r]->getRoomTypeDescription();
			$smoking = $allRoomTypes[$r]->getSmokingYN();
			if($availableRoomtypeCount[$roomTypeId] > 0) { // this room type has available rooms, so add the room type to the array.
				$roomtypeInfo_array['roomTypeCode'] = $roomTypeId;
				$roomtypeInfo_array['roomRate'] = $standardRate;
				$roomtypeInfo_array['roomTypeDescription'] = $description;
				$roomtypeInfo_array['smokingYN'] = $smoking;
				$roomtypeInfo_array['numAvailableRooms'] = $availableRoomtypeCount[$roomTypeId];
				array_push($roomtypes_array, $roomtypeInfo_array);
			}
		}
		$hotel_array['roomtype_info'] = $roomtypes_array;
		array_push($return_arr, $hotel_array);
	}
	
	print json_encode($return_arr);
}
else {
	$error = true;
	print json_encode($message);
}
?>
